<template>
  <div class="custom-list-container">
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服装类型">
          <el-select v-model="filterForm.clothingType" placeholder="选择类型" clearable>
            <el-option
              v-for="item in clothingTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div slot="header" class="card-header">
        <span>我的定制申请</span>
        <el-button type="primary" size="small" @click="$router.push('/custom/submit')">新增定制</el-button>
      </div>
      
      <el-table
        :data="customList"
        border
        v-loading="loading"
        style="width: 100%">
        <el-table-column
          prop="id"
          label="编号"
          width="80">
        </el-table-column>
        <el-table-column
          prop="clothingType"
          label="服装类型"
          width="120">
          <template slot-scope="scope">
            {{ getTypeName(scope.row.clothingType) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="申请时间"
          width="180">
        </el-table-column>
        <el-table-column
          prop="budget"
          label="预算"
          width="120">
          <template slot-scope="scope">
            ¥ {{ scope.row.budget }}
          </template>
        </el-table-column>
        <el-table-column
          prop="deliveryDate"
          label="预计交付"
          width="120">
        </el-table-column>
        <el-table-column
          prop="designer"
          label="设计师"
          width="120">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusName(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="进度"
          width="200">
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)"></el-progress>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleDetail(scope.row)">详情</el-button>
            <el-button
              size="mini"
              type="success"
              v-if="scope.row.status === 'design_completed'"
              @click="handleConfirm(scope.row)">确认设计</el-button>
            <el-button
              size="mini"
              type="danger"
              v-if="['pending', 'design_in_progress'].includes(scope.row.status)"
              @click="handleCancel(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog title="定制详情" :visible.sync="detailDialogVisible" width="70%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="编号">{{ currentCustom.id }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentCustom.createTime }}</el-descriptions-item>
        <el-descriptions-item label="服装类型">{{ getTypeName(currentCustom.clothingType) }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ getGenderName(currentCustom.gender) }}</el-descriptions-item>
        <el-descriptions-item label="尺码">{{ currentCustom.size.standard }}</el-descriptions-item>
        <el-descriptions-item label="面料">{{ getFabricName(currentCustom.fabric) }}</el-descriptions-item>
        <el-descriptions-item label="颜色">
          <span class="color-box" :style="{backgroundColor: currentCustom.color}"></span>
          {{ currentCustom.color }}
        </el-descriptions-item>
        <el-descriptions-item label="设计风格">{{ getStyleName(currentCustom.style) }}</el-descriptions-item>
        <el-descriptions-item label="预算">¥ {{ currentCustom.budget }}</el-descriptions-item>
        <el-descriptions-item label="预计交付">{{ currentCustom.deliveryDate }}</el-descriptions-item>
        <el-descriptions-item label="设计师">{{ currentCustom.designer }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentCustom.status)">{{ getStatusName(currentCustom.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="特殊要求">{{ currentCustom.specialRequirements || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="detail-section" v-if="currentCustom.referenceImages && currentCustom.referenceImages.length > 0">
        <div class="section-title">参考图片</div>
        <div class="image-list">
          <div class="image-item" v-for="(img, index) in currentCustom.referenceImages" :key="index">
            <el-image :src="img" :preview-src-list="currentCustom.referenceImages"></el-image>
          </div>
        </div>
      </div>
      
      <div class="detail-section" v-if="currentCustom.designImages && currentCustom.designImages.length > 0">
        <div class="section-title">设计图稿</div>
        <div class="image-list">
          <div class="image-item" v-for="(img, index) in currentCustom.designImages" :key="index">
            <el-image :src="img" :preview-src-list="currentCustom.designImages"></el-image>
          </div>
        </div>
      </div>
      
      <div class="detail-section">
        <div class="section-title">进度记录</div>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in currentCustom.activities"
            :key="index"
            :timestamp="activity.time"
            :type="activity.type"
            :color="activity.color">
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <div class="detail-section" v-if="currentCustom.status === 'design_completed'">
        <div class="section-title">确认信息</div>
        <div class="confirm-box">
          <p>设计师已完成设计，请确认是否满意？</p>
          <el-button type="success" @click="handleConfirmInDialog">确认设计</el-button>
          <el-button type="warning" @click="handleRequestRevision">申请修改</el-button>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    
    <!-- 申请修改对话框 -->
    <el-dialog title="申请修改" :visible.sync="revisionDialogVisible" width="50%">
      <el-form :model="revisionForm" label-width="100px">
        <el-form-item label="修改原因" required>
          <el-input type="textarea" :rows="4" v-model="revisionForm.reason" placeholder="请详细描述您希望修改的内容和原因..."></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="revisionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRevision">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CustomList',
  data() {
    return {
      loading: false,
      filterForm: {
        status: '',
        clothingType: '',
        dateRange: []
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      customList: [],
      statusOptions: [
        { value: 'pending', label: '待接受' },
        { value: 'design_in_progress', label: '设计中' },
        { value: 'design_completed', label: '设计完成' },
        { value: 'production', label: '生产中' },
        { value: 'delivered', label: '已交付' },
        { value: 'cancelled', label: '已取消' }
      ],
      clothingTypes: [
        { value: 'shirt', label: '衬衫' },
        { value: 'tshirt', label: 'T恤' },
        { value: 'dress', label: '连衣裙' },
        { value: 'suit', label: '西装' },
        { value: 'pants', label: '裤子' },
        { value: 'coat', label: '外套' },
        { value: 'skirt', label: '裙子' }
      ],
      fabricTypes: [
        { value: 'cotton', label: '棉' },
        { value: 'linen', label: '亚麻' },
        { value: 'silk', label: '丝绸' },
        { value: 'wool', label: '羊毛' },
        { value: 'polyester', label: '聚酯纤维' },
        { value: 'denim', label: '牛仔布' },
        { value: 'leather', label: '皮革' }
      ],
      styleTypes: [
        { value: 'casual', label: '休闲' },
        { value: 'formal', label: '正式' },
        { value: 'business', label: '商务' },
        { value: 'sports', label: '运动' },
        { value: 'vintage', label: '复古' },
        { value: 'bohemian', label: '波西米亚' },
        { value: 'minimalist', label: '极简' }
      ],
      detailDialogVisible: false,
      revisionDialogVisible: false,
      currentCustom: {},
      revisionForm: {
        reason: ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.loading = true
      
      // 模拟后端数据
      setTimeout(() => {
        const mockData = [
          {
            id: 'C-20230501-001',
            clothingType: 'dress',
            gender: 'female',
            size: { standard: 'M' },
            fabric: 'silk',
            color: '#FF5733',
            style: 'formal',
            budget: 2800,
            createTime: '2023-05-01 10:23:45',
            deliveryDate: '2023-05-30',
            designer: '王艺',
            status: 'design_completed',
            progress: 70,
            specialRequirements: '希望有精致的蕾丝边，优雅大方',
            referenceImages: ['https://picsum.photos/id/237/200/300', 'https://picsum.photos/id/238/200/300'],
            designImages: ['https://picsum.photos/id/239/200/300', 'https://picsum.photos/id/240/200/300'],
            activities: [
              { content: '提交定制申请', time: '2023-05-01 10:23:45', type: 'primary', color: '#409EFF' },
              { content: '系统分配设计师：王艺', time: '2023-05-02 09:15:30', type: 'info', color: '#909399' },
              { content: '设计师开始设计', time: '2023-05-03 14:22:10', type: 'warning', color: '#E6A23C' },
              { content: '设计师提交初稿', time: '2023-05-10 16:42:18', type: 'success', color: '#67C23A' }
            ]
          },
          {
            id: 'C-20230420-002',
            clothingType: 'suit',
            gender: 'male',
            size: { standard: 'L' },
            fabric: 'wool',
            color: '#3D85C6',
            style: 'business',
            budget: 3500,
            createTime: '2023-04-20 15:30:22',
            deliveryDate: '2023-05-25',
            designer: '李敏',
            status: 'production',
            progress: 85,
            specialRequirements: '适合商务场合，需要挺括有型',
            referenceImages: ['https://picsum.photos/id/241/200/300'],
            designImages: ['https://picsum.photos/id/242/200/300', 'https://picsum.photos/id/243/200/300'],
            activities: [
              { content: '提交定制申请', time: '2023-04-20 15:30:22', type: 'primary', color: '#409EFF' },
              { content: '系统分配设计师：李敏', time: '2023-04-21 10:12:45', type: 'info', color: '#909399' },
              { content: '设计师开始设计', time: '2023-04-22 09:33:29', type: 'warning', color: '#E6A23C' },
              { content: '设计师提交设计', time: '2023-04-30 16:42:18', type: 'success', color: '#67C23A' },
              { content: '确认设计并进入生产', time: '2023-05-02 14:15:33', type: 'success', color: '#67C23A' }
            ]
          },
          {
            id: 'C-20230415-003',
            clothingType: 'tshirt',
            gender: 'unisex',
            size: { standard: 'M' },
            fabric: 'cotton',
            color: '#74C365',
            style: 'casual',
            budget: 980,
            createTime: '2023-04-15 09:12:38',
            deliveryDate: '2023-05-10',
            designer: '张鑫',
            status: 'delivered',
            progress: 100,
            specialRequirements: '简约风格，适合日常穿着',
            referenceImages: ['https://picsum.photos/id/244/200/300'],
            designImages: ['https://picsum.photos/id/245/200/300'],
            activities: [
              { content: '提交定制申请', time: '2023-04-15 09:12:38', type: 'primary', color: '#409EFF' },
              { content: '系统分配设计师：张鑫', time: '2023-04-16 10:22:45', type: 'info', color: '#909399' },
              { content: '设计师开始设计', time: '2023-04-17 11:33:29', type: 'warning', color: '#E6A23C' },
              { content: '设计师提交设计', time: '2023-04-21 15:42:18', type: 'success', color: '#67C23A' },
              { content: '确认设计并进入生产', time: '2023-04-22 13:15:33', type: 'success', color: '#67C23A' },
              { content: '生产完成并发货', time: '2023-05-05 09:40:12', type: 'success', color: '#67C23A' },
              { content: '客户确认收货', time: '2023-05-09 16:20:55', type: 'success', color: '#67C23A' }
            ]
          },
          {
            id: 'C-20230510-004',
            clothingType: 'coat',
            gender: 'female',
            size: { standard: 'S' },
            fabric: 'leather',
            color: '#000000',
            style: 'vintage',
            budget: 4200,
            createTime: '2023-05-10 13:45:28',
            deliveryDate: '2023-06-10',
            designer: '',
            status: 'pending',
            progress: 10,
            specialRequirements: '复古皮夹克，有做旧效果',
            referenceImages: ['https://picsum.photos/id/246/200/300', 'https://picsum.photos/id/247/200/300'],
            designImages: [],
            activities: [
              { content: '提交定制申请', time: '2023-05-10 13:45:28', type: 'primary', color: '#409EFF' }
            ]
          }
        ]
        
        this.customList = mockData
        this.pagination.total = mockData.length
        this.loading = false
      }, 800)
    },
    handleSearch() {
      this.fetchData()
    },
    resetFilter() {
      this.filterForm = {
        status: '',
        clothingType: '',
        dateRange: []
      }
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    handleDetail(row) {
      this.currentCustom = JSON.parse(JSON.stringify(row))
      this.detailDialogVisible = true
    },
    handleConfirm(row) {
      this.$confirm('确认设计后将进入生产阶段，是否确认?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.$message.success('已确认设计，订单将进入生产阶段')
        // 这里应该调用API更新状态
        const index = this.customList.findIndex(item => item.id === row.id)
        if (index !== -1) {
          this.customList[index].status = 'production'
          this.customList[index].progress = 85
          this.customList[index].activities.push({
            content: '确认设计并进入生产',
            time: this.formatDate(new Date()),
            type: 'success',
            color: '#67C23A'
          })
        }
      }).catch(() => {})
    },
    handleCancel(row) {
      this.$confirm('取消后将无法恢复，是否确认取消该定制申请?', '警告', {
        confirmButtonText: '确认取消',
        cancelButtonText: '返回',
        type: 'warning'
      }).then(() => {
        this.$message.success('已取消定制申请')
        // 这里应该调用API更新状态
        const index = this.customList.findIndex(item => item.id === row.id)
        if (index !== -1) {
          this.customList[index].status = 'cancelled'
          this.customList[index].progress = 0
          this.customList[index].activities.push({
            content: '用户取消定制申请',
            time: this.formatDate(new Date()),
            type: 'danger',
            color: '#F56C6C'
          })
        }
      }).catch(() => {})
    },
    handleConfirmInDialog() {
      this.handleConfirm(this.currentCustom)
      this.detailDialogVisible = false
    },
    handleRequestRevision() {
      this.revisionDialogVisible = true
    },
    submitRevision() {
      if (!this.revisionForm.reason) {
        this.$message.warning('请填写修改原因')
        return
      }
      
      this.$message.success('已提交修改申请，等待设计师处理')
      // 这里应该调用API提交修改申请
      const index = this.customList.findIndex(item => item.id === this.currentCustom.id)
      if (index !== -1) {
        this.customList[index].activities.push({
          content: `用户申请修改：${this.revisionForm.reason}`,
          time: this.formatDate(new Date()),
          type: 'warning',
          color: '#E6A23C'
        })
        this.customList[index].status = 'design_in_progress'
        this.customList[index].progress = 60
      }
      
      this.revisionDialogVisible = false
      this.detailDialogVisible = false
      this.revisionForm.reason = ''
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    getTypeName(type) {
      const found = this.clothingTypes.find(item => item.value === type)
      return found ? found.label : type
    },
    getGenderName(gender) {
      const map = { male: '男装', female: '女装', unisex: '中性' }
      return map[gender] || gender
    },
    getFabricName(fabric) {
      const found = this.fabricTypes.find(item => item.value === fabric)
      return found ? found.label : fabric
    },
    getStyleName(style) {
      const found = this.styleTypes.find(item => item.value === style)
      return found ? found.label : style
    },
    getStatusName(status) {
      const found = this.statusOptions.find(item => item.value === status)
      return found ? found.label : status
    },
    getStatusType(status) {
      const map = {
        pending: 'info',
        design_in_progress: 'warning',
        design_completed: 'success',
        production: 'primary',
        delivered: 'success',
        cancelled: 'danger'
      }
      return map[status] || 'info'
    },
    getProgressStatus(progress) {
      if (progress === 100) return 'success'
      if (progress > 80) return 'success'
      if (progress > 40) return 'warning'
      return 'exception'
    }
  }
}
</script>

<style scoped>
.custom-list-container {
  padding: 20px;
  box-sizing: border-box;
  min-height: calc(100vh - 60px);
  background-color: var(--page-background);
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.color-box {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  margin-right: 10px;
  border: 1px solid #ddd;
  vertical-align: middle;
}

.detail-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item {
  width: 150px;
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.image-item .el-image {
  width: 100%;
  height: 100%;
}

.confirm-box {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 10px;
}

.confirm-box p {
  margin-bottom: 15px;
}
</style>